package com.github.shuaidd.service.runtime;

import com.github.shuaidd.service.mapper.CommentMapperService;
import lombok.RequiredArgsConstructor;
import org.activiti.app.domain.runtime.Comment;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.Clock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 描述
 *
 * @author ddshuai
 * @date 2020-07-20 22:28
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class LwfCommentService {
    private final CommentMapperService commentRepository;

    private final Clock clock;

    public Long countCommentsForTask(String taskId) {
        return commentRepository.countByTaskId(taskId);
    }

    public Long countCommentsForProcessInstance(String processInstanceId) {
        return commentRepository.countByProcessInstanceId(processInstanceId);
    }

    public List<Comment> getCommentsForTask(String taskId, boolean latestFirst) {
        return commentRepository.findByTaskId(taskId, commentRepository.getOrderByFormat(new Sort((latestFirst ? Sort.Direction.DESC : Sort.Direction.ASC),Comment.PROPERTY_CREATED)));
    }

    public List<Comment> getCommentsForProcessInstance(String processInstanceId, boolean latestFirst) {
        return commentRepository.findByProcessInstanceId(processInstanceId, commentRepository.getOrderByFormat(new Sort((latestFirst ? Sort.Direction.DESC : Sort.Direction.ASC), Comment.PROPERTY_CREATED)));
    }

    public Comment createComment(String message, User createdBy, String processInstanceId) {
        return createComment(message, createdBy, null, processInstanceId);
    }

    public Comment createComment(String message, User createdBy, String taskId, String processInstanceId) {
        Comment newComment = new Comment();
        newComment.setMessage(message);
        newComment.setCreatedBy(createdBy.getId());
        newComment.setCreated(clock.getCurrentTime());
        newComment.setTaskId(taskId);
        newComment.setProcessInstanceId(processInstanceId);

        commentRepository.insert(newComment);
        return newComment;
    }

    public void deleteComment(Comment comment) {
        commentRepository.deleteByPrimaryKey(comment.getId());
    }

    /**
     * Deletes all comments related to the given process instance. Includes both comments on the process instance itself
     * and any comments on the tasks in that process.
     */
    @Transactional
    public void deleteAllCommentsForProcessInstance(String processInstanceId) {
        commentRepository.deleteAllByProcessInstanceId(processInstanceId);
    }
}
